package com.xinziruo.crawl.infrastruture.messaging.event;

import java.util.ArrayList;
import java.util.List;

import org.springframework.util.Assert;

import com.xinziruo.crawl.domain.crawl.api.CrawlEvent;
import com.xinziruo.crawl.domain.crawl.api.CrawlEventFilter;
import com.xinziruo.crawl.domain.crawl.api.CrawlEventFilterChain;
import com.xinziruo.crawl.domain.crawl.api.CrawlEventHandler;

/**
 * 
 * @author loudyn
 * 
 */
public class CrawlEventFilterChainImpl implements CrawlEventFilterChain {
	private List<CrawlEventFilter> crawlEventFilters = new ArrayList<CrawlEventFilter>();
	private CrawlEventHandler handler;
	private int position = 0;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.youboy.crawl.domain.crawl.api.CrawlEventFilterChain#getHandler()
	 */
	@Override
	public CrawlEventHandler getHandler() {
		return handler;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.youboy.crawl.infrastruture.crawl.CrawlEventFilterChain#filter(com.youboy
	 * .crawl.infrastruture.crawl.CrawlEvent
	 * )
	 */
	@Override
	public void filter(CrawlEvent crawlEvent) {
		if (position < crawlEventFilters.size()) {
			position++;

			CrawlEventFilter nextFilter = crawlEventFilters.get(position - 1);
			nextFilter.filter(crawlEvent, this);
		}

	}

	/**
	 * 
	 * @param crawlEventFilter
	 * @return
	 */
	public CrawlEventFilterChainImpl addCrawlEventFilter(CrawlEventFilter crawlEventFilter) {
		crawlEventFilters.add(crawlEventFilter);
		return this;
	}

	/**
	 * 
	 * @param filters
	 * @return
	 */
	public void setCrawlEventFilters(List<CrawlEventFilter> filters) {
		Assert.notNull(filters, "filters must not null");
		this.crawlEventFilters = filters;
	}

	/**
	 * 
	 * @param handler
	 */
	public void setHandler(CrawlEventHandler handler) {
		Assert.notNull(handler, "handler must not null");
		this.handler = handler;
	}

}
